//
//  WJPdfGenerator.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/26.
//

import UIKit

class WJPdfGenerator {
    
    static func createPDFAndSaveToDatabase(from images: [UIImage], open: Bool, complation: ((Bool) -> Void)?) {
        let timeStamp = Int(Date().timeIntervalSince1970)
        let success = WJPdfGenerator.createPDF(from: images, timeStamp: timeStamp)
         
         let desiredSize = CGSize(width: 120, height: 160)
         if success,
            let destinationURL = WJPdfGenerator.getPDFFileURL(timeStamp) {
             WJPDFThumbnailGenerator.generate(from: destinationURL, thumbnailSize: desiredSize) { (thumbnail, fileSize) in
                 let listModel = WJPDFListModel()
                 listModel.imageData = thumbnail?.pngData() ?? Data()
                 listModel.name = WJPdfGenerator.fileName(timeStamp)
                 listModel.suffix = "pdf"
                 listModel.fileSize = fileSize ?? 0
                 listModel.filePath = WJPdfGenerator.relativePath(timeStamp)
                 listModel.signState = false
                 // 保存到数据库
                 let id = try? listModel.save()
                 listModel.id = id ?? 0
                 
                 if open {
                     NotificationCenter.default.post(name: .pdfListChangedNotification, object: listModel)
                 } else {
                     NotificationCenter.default.post(name: .pdfListChangedNotification, object: nil)
                 }
                 complation?(true)
             }
         } else {
             complation?(false)
         }
    }
    
    /// 将多张图片生成PDF，每页一张图片
    @discardableResult
    static func createPDF(from images: [UIImage], pageSize: CGSize = CGSize(width: 595, height: 842), timeStamp: Int) -> Bool {
        
        // 1. 获取最终PDF文件的目标URL
        guard let outputURL = getPDFFileURL(timeStamp) else {
            print("❌ 无法生成PDF文件路径")
            return false
        }
        
        let renderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: pageSize))
        
        do {
            // 2. 尝试写入PDF文件
            try renderer.writePDF(to: outputURL) { context in
                for image in images {
                    context.beginPage()
                    let imageSize = calculateImageSize(image: image, in: pageSize)
                    let imageRect = CGRect(origin: .zero, size: imageSize)
                        .centered(in: CGRect(origin: .zero, size: pageSize))
                    image.draw(in: imageRect)
                }
            }
            print("✅ PDF生成成功: \(outputURL.path)")
            return true
        } catch {
            print("❌ PDF生成失败: \(error.localizedDescription)")
            return false
        }
    }

    static func getPDFFileURL(_ timeStamp: Int) -> URL? {
        // 获取Documents目录
        guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        
        let pdfDirectoryURL = documentsURL.appendingPathComponent(folderPath(), isDirectory: true)

        // 确保目标目录存在
        do {
            try FileManager.default.createDirectory(at: pdfDirectoryURL, withIntermediateDirectories: true)
        } catch {
            print("❌ 创建目录失败: \(error.localizedDescription)")
            return nil
        }
        
        let fileName = fileName(timeStamp)
        
        return pdfDirectoryURL.appendingPathComponent(fileName)
    }
    
    /// 计算图片在页面中的合适尺寸
    private static func calculateImageSize(image: UIImage, in pageSize: CGSize) -> CGSize {
        let imageAspect = image.size.width / image.size.height
        let pageAspect = pageSize.width / pageSize.height
        
        if imageAspect > pageAspect {
            // 图片比页面宽，以宽度为准
            let width = pageSize.width - 40 // 留边距
            let height = width / imageAspect
            return CGSize(width: width, height: height)
        } else {
            // 图片比页面高，以高度为准
            let height = pageSize.height - 40 // 留边距
            let width = height * imageAspect
            return CGSize(width: width, height: height)
        }
    }
    
    static func relativePath(_ timeStamp: Int) -> String {
        let fileName = fileName(timeStamp)
        let relativePath = folderPath() + "/" + fileName
        return relativePath
    }
    
    static func folderPath() -> String {
        let folderPath = "PDF/Images"
        return folderPath
    }
    
    static func fileName(_ timeStamp: Int) -> String {
        let fileName = "Scan" + "_" + "\(timeStamp)" + ".pdf"
        return fileName
    }
}

// CGRect扩展：居中计算
extension CGRect {
    func centered(in rect: CGRect) -> CGRect {
        let dx = rect.midX - midX
        let dy = rect.midY - midY
        return offsetBy(dx: dx, dy: dy)
    }
}

